#include "util.h"
#include <string>
#include <time.h>
#include <windows.h>

string util::RandomString(int stringlen)
{
	// Initializing random by using time as beginning value
#ifndef _radom_init_done
#define _radom_init_done
	srand(time(NULL));
	srand(static_cast<int>(time(NULL)));
#endif

	char characters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
						'A', 'B', 'B', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
	string random;
	
	for(int i=0; i<stringlen; i++)
	{
		random += characters[0 + rand() % (sizeof(characters) - 0 + 1)];
	}
	random += ".exe";
	return random;
}

bool util::CheckMutex(string mutex)
{
	HANDLE check;
	check = CreateMutex(NULL, true, mutex.c_str());
	if(GetLastError() == ERROR_ALREADY_EXISTS)
		return false;
	else
		return true;
}


string* util::SplitString(string data, string delimiter, int* length)
{
	// check if delimiter exists, otherwise exit function
	if(data.find(delimiter) == -1)
	{
		*length = -1;
		return NULL;
	}

	// declaring some variables
	int counter = 0;
	int pos = 0;
	int pos2;
	string *result = NULL;

	// find out how many limiters are in the string
	while(data.find(delimiter, pos) != -1)
	{
		counter++;
		pos = data.find(delimiter, pos+1);
	}
	

	// initializing dynamic array with counter - elements
	*length = counter;
	result = new string[counter];
	
	// split strings and save them in the array
	pos = 0;
	for(int i=0; i<counter; i++)
	{

		pos2 = data.find(delimiter, pos+delimiter.length() );
		result[i] = data.substr(pos, (pos2-pos));
		pos = pos2+delimiter.length();

	}
	return result;
}